import { useEffect, useState, useRef } from 'react';
import { message } from 'antd';
import { ProFormText, ModalForm, ProFormSwitch, ProFormSelect } from '@ant-design/pro-components';
import { isLocal, isSuccess } from '@/utils';
import { AddUserApi } from '@/api';

export default function AddStaff({ open, setOpen, formData, reload, zhimaList }: any) {
  const [txt, setTxt] = useState('');
  const formRef: any = useRef('');
  console.log('formData: ', formData);

  useEffect(() => {
    setTxt(formData?.id ? '编辑' : '新增');
    if (open) initData();
  }, [open]);

  // 初始化数据
  const initData = () => {
    formRef?.current?.resetFields();
    if (formData?.id) {
      formData.direction = formData?.direction + '';
      formRef?.current?.setFieldsValue(formData);
      return;
    }
    // 新增
    formRef?.current?.setFieldsValue({
      is_active: true,
    });
    if (isLocal()) {
      formRef?.current?.setFieldsValue({
        name: 'yuanGong2',
        password: '123456',
        passwordRepeat: '123456',
        direction: '1',
        zhiMaId: '1',
      });
    }
  };

  // 提交
  const submit = async () => {
    let val = await formRef?.current?.validateFieldsReturnFormatValue();
    console.log('格式化后的表单数据: ', val);
    // 新增、编辑
    let params: any = !formData?.id ? val : { ...val, id: formData?.id };
    // 重复密码校验
    if (!formData?.id) {
      if (params.password !== params.passwordRepeat) {
        message.error('两次密码输入不一致');
        return;
      }
    } else {
      params.password = formData.password;
    }
    let res: any = await AddUserApi(params);
    if (!isSuccess(res)) return;
    message.success(txt + '成功');
    reload();
    setOpen(false);
  };

  return (
    <ModalForm
      title={`${txt}`}
      formRef={formRef}
      open={open}
      layout="horizontal"
      onFinish={submit}
      onOpenChange={setOpen}
      labelCol={{ span: 4 }}
    >
      <br />
      <ProFormText name="name" label="账号" placeholder="请输入" rules={[{ required: true }]} />
      {!formData?.id && (
        <>
          <ProFormText
            name="password"
            label="密码"
            placeholder="请输入"
            rules={[{ required: true }]}
          />
          <ProFormText
            name="passwordRepeat"
            label="重复密码"
            placeholder="请输入"
            rules={[{ required: true }]}
          />
        </>
      )}
      <ProFormSelect
        name="direction"
        label="交易方向"
        valueEnum={{ '1': '正向', '-1': '反向' }}
        placeholder="请选择"
        rules={[{ required: true }]}
      />
      <ProFormSelect
        name="zhiMaId"
        label="关联芝麻"
        valueEnum={zhimaList}
        placeholder="请选择"
        // rules={[{ required: true }]}
      />
      <ProFormSwitch name="is_active" label="是否开启" rules={[{ required: true }]} />
    </ModalForm>
  );
}
